package com.lfy.config;

import lombok.extern.slf4j.Slf4j;
import org.quartz.Scheduler;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.io.IOException;
import java.util.Properties;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author lfy
 */
@Configuration
@Slf4j
public class SchedulerConfig {
    @Resource
    private DataSource dataSource;
    @Resource(name = "mainThreadPool")
    private ThreadPoolExecutor mainThreadPool;


    /**
     * quartz调度器
     * @return Scheduler调度器
     */
    @Bean("scheduler")
    public Scheduler scheduler() {
        return schedulerFactoryBean().getScheduler();
    }

    /**
     * scheduler工厂
     * @return SchedulerFactoryBean
     */
    @Bean
    public SchedulerFactoryBean schedulerFactoryBean() {
        SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();
        schedulerFactoryBean.setSchedulerName("global_scheduler");
        schedulerFactoryBean.setDataSource(dataSource);
        schedulerFactoryBean.setTaskExecutor(mainThreadPool);
        schedulerFactoryBean.setApplicationContextSchedulerContextKey("quartz_context");
        schedulerFactoryBean.setQuartzProperties(quartzProperties());
        //延迟执行
        schedulerFactoryBean.setStartupDelay(10);


        return schedulerFactoryBean;
    }

    /**
     * quartz配置文件
     * @return Properties
     */
    @Bean
    public Properties quartzProperties() {
        PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
        propertiesFactoryBean.setLocation(new ClassPathResource("/quartz.properties"));
        try {
            propertiesFactoryBean.afterPropertiesSet();
        } catch (IOException e) {
            log.error("quartz.properties not found", e);
        }
        Properties properties = null;
        try {
             properties = propertiesFactoryBean.getObject();
        } catch (IOException e) {
            log.error("quartz.properties not found", e);
        }

        return properties;
    }
}
